package;
import lovedna.game.components.Component;
import lovedna.game.events.ActorEvent;
import lovedna.media.AudioClip;
import lovedna.resource.Assets;
import lovedna.utils.Helper;
import table.TableClass.TableItemData;
import table.Tables;


/**
 * ... 
 * @author liwei
 */
class Sound extends Component
{
	/*======constants============================*/
	
	/*======static ==============================*/
	
	/*======Public===============================*/
	public var onBeat:Void->Void;
	/*======Private==============================*/
	private var _audio:AudioClip;
	private var _data:TableItemData;
	private var _index:Int;
	private var _nextTime:Float;
	private var _lt:Float;
	public function new() 
	{
		super();
		
	}
	/*======Public Static methods================*/
	
	/*======Public methods=======================*/
	public function play(id:Int):Void
	{
		//trace("play");
		_audio.load(Assets.audio.get("audio/level" + id + ".mp3").audio);
		_audio.play();
		//_audio.currentTime = 50;
		//_audio.rate = 1.2;
		_data = Tables.item.get(id);
		_index = 0;
		_nextTime = _data.value[_index];
		_lt = _nextTime;
		bindEvent(ActorEvent.onUpdate, onUpdate);
	}
	/*======public override methods==============*/
	
	/*======private override methods=============*/
	override function onAwake():Void 
	{
		super.onAwake();
		_audio = new AudioClip();
		_dt = 0;
	}
	
	/*======Private methods======================*/
	private var _dt:Float;
	private function onUpdate(?e):Void
	{
		var t:Float = _audio.currentTime;
		//trace(t - _dt, actor.deltaTime);
		_dt = t;
		if (t >= _nextTime)
		{
			if (onBeat != null)
			{
				onBeat();
			}
			trace(Helper.formatTime(_nextTime));
			if (_index < _data.value.length)
			{
				_index++;
				_nextTime = _data.value[_index];
			}else
			{
				_nextTime = _audio.duration;
			}
			_lt = _nextTime;
		}
	}
	/*======get set methods======================*/
	
}